package com.geezdata.cps.base.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SSLUtil {
	private static Logger logger = LoggerFactory.getLogger(SSLUtil.class);
   
	public static SSLConnectionSocketFactory sslConnectionSocketFactory(
			String keyStorePath, String keyStorePassword, String keyStoreType) {
		try {
			KeyStore keyStore = keyStore(keyStorePath, keyStorePassword, keyStoreType);
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(  
					SSLContexts.custom().loadKeyMaterial(keyStore, keyStorePassword.toCharArray()).build(),  
			        new String[] { "TLSv1" },  
			        null,  
			        SSLConnectionSocketFactory.getDefaultHostnameVerifier());
			return sslsf;
		} catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
				| CertificateException | IOException e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}  
		
		return null;
	}
	
	private static KeyStore keyStore(String keyStorePath, String keyStorePassword, String keyStoreType) 
			throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
//		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//		InputStream inputStream = request.getSession().getServletContext().getResourceAsStream(keyStorePath);
		InputStream inputStream = new FileInputStream(new File(keyStorePath));
		KeyStore keyStore  = KeyStore.getInstance(keyStoreType);  
        try {  
            keyStore.load(inputStream, keyStorePassword.toCharArray());  
        }  finally {  
        	inputStream.close();  
        }
        
		return keyStore; 
	}
}
